package org.dashboard.client.widget.messageflow;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Node;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import org.dashboard.client.widget.ImageWidget;

/**
 * @author Simon Vogensen, Lakeside
 * @version $Revision$
 */
public class NewAndProcessingMessageFlowWidget extends ImageWidget {

    interface Binder extends UiBinder<Widget, NewAndProcessingMessageFlowWidget> { }
    private static final Binder binder = GWT.create(Binder.class);

    public NewAndProcessingMessageFlowWidget(final int width, final int height, int refreshInterval) {
        super();

        setWidget(binder.createAndBindUi(this));

        Node node = getElement().getChild(0);
        DOM.setStyleAttribute((Element) node, "width", width+"px");
        DOM.setStyleAttribute((Element) node, "height", height+"px");

        final MessageFlowServiceAsync instance = (MessageFlowServiceAsync) GWT.create(MessageFlowService.class);

        final AsyncCallback<String> flowCallback = new AsyncCallback<String>() {
            public String oldResult;

            public void onFailure(Throwable caught) {}

            public void onSuccess(String result) {
                if(!result.equals(oldResult)) {
                    replaceImageNoCache(result);
                }
                this.oldResult = result;
            }
        };

        final Timer timer = new Timer() {
            @Override
            public void run() {
                instance.getNewAndProcessingGraph(flowCallback); ;
            }
        };
        timer.scheduleRepeating(refreshInterval);
        instance.getNewAndProcessingGraph(flowCallback);
    }
}
